package com.lf.api.util;

import java.security.MessageDigest;

import org.apache.commons.lang3.RandomStringUtils;

/**
 * 
 * Description: 通用的工具方法类
 * 1、MD5加密
 * 2、SHA加密
 * 
 * Copyright: Copyright (c)2012
 * Company: 小小书童
 * @author: 小小书童
 * @version: 1.0
 * Create at: 2016年9月16日 下午11:18:48
 *
 * Modification History:
 * Date Author Version Description
 * ---------------------------修改历史---------------------------------------
 * 2016年9月16日 小小书童 1.0
 */
public final class CommonUtil {
	public static String randomNumbers(){
		return RandomStringUtils.random(4, "0123456789abcedfgh");
	}

	/**
	 * 
	 * Description:	MD5加密
	 * Date:2016年9月16日
	 * @author 小小书童
	 * @return String
	 */
	public static String md5Encode(String password, String salt) throws Exception {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}

		byte[] byteArray = (password + salt).getBytes("UTF-8");
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	public static String shaEncode(String password, String salt) throws Exception {
		MessageDigest sha = null;
		try {
			sha = MessageDigest.getInstance("SHA");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}

		byte[] byteArray = (password + salt).getBytes("UTF-8");
		byte[] md5Bytes = sha.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}
	
	public static void main(String[] args) throws Exception {
		/*for(int i=0;i<10;i++){
			System.out.println(randomNumbers());
		}*/
		for(int i=0;i<10;i++){
			String randomStr = randomNumbers();
			System.out.print(randomStr + "==");
			System.out.println(md5Encode("123456", randomStr));
		}
		System.out.println("====================================");
		for(int i=0;i<10;i++){
			String randomStr = randomNumbers();
			System.out.print(randomStr + "==");
			System.out.println(md5Encode("123456", randomStr));
		}
	}
}
